package cn.newgrand.netcall.imp.search.contact;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.JTextComponent;

import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.ui.ContactItem;
import org.jivesoftware.spark.ui.ContactList;
import org.jivesoftware.spark.util.PositionCalculator;
import org.jivesoftware.spark.util.StringUtils;
import org.jivesoftware.spark.util.log.Log;

import cn.newgrand.netcall.search.contact.ContactSearchManager;

/**
 * @author SidneyRen E-mail:SidneyRen@hotmail.com
 * @version create time：2010-8-2 下午01:55:51 
 * 
 * 
 * 
 */
public class ContactSearchResultPanel extends JPanel {

	private final DefaultListModel model = new DefaultListModel();
	private JList contacts;
	private Map<JLabel, String> jidMap = new HashMap<JLabel, String>();
	private String temp ="";
	private List<MouseListener> mouseListens = new ArrayList<MouseListener>();
	private List<MouseListener> keyListens = new ArrayList<MouseListener>();
	public ContactSearchResultPanel() {
		
		setOpaque(true);
		setBackground(Color.WHITE);
		setLayout(new BorderLayout());
		contacts = new JList();
		contacts.setBorder(new EmptyBorder(0,3,0,3));
		contacts.setCellRenderer(new InternalRenderer());
		add(contacts, BorderLayout.NORTH);
		setBorder(BorderFactory.createLineBorder(Color.gray));
		contacts.addFocusListener(new FocusListener() {
			public void focusGained(FocusEvent e) {
			}

			public void focusLost(FocusEvent e) {
				setVisible(false);
			}
		});
	}
	
	/**
	 * 展示查询结果
	 * 
	 * @param str
	 */
	public void showResults(String searchStr){
		if(null==searchStr||searchStr.equals("")){
			setVisible(false);
			return ;
		}
		List<String> strList = new ArrayList<String>();
		strList = ContactSearchManager.getInstance().getContactSearch().getContactsJID(searchStr);
		showResults(strList);
	}
	
	/**
	 * 在面板上显示查询的结果
	 * 
	 * @param resultStrList 查询所得的，以JID形式存储的联系人结果集
	 * 
	 */
	public void showResults(Collection<String> resultStrList) {
		
		//清除查询显示的结果
		jidMap.clear();
		model.clear();
		final ContactList contactList = SparkManager.getWorkspace()
				.getContactList();
		if (null != resultStrList) {
			for (final String user : resultStrList) {
				ContactItem contactItem = contactList.getContactItemByJID(user);
				Icon icon;
				if (contactItem != null) {
					icon = contactItem.getIcon();
					if (icon == null) {
						icon = SparkRes.getImageIcon(SparkRes.CLEAR_BALL_ICON);
					}

					JLabel label = new JLabel();
					label.setText(StringUtils.combineWithBracket(contactItem.getDisplayName(), user));
					label.setIcon(icon);
					model.addElement(label);
					jidMap.put(label, user);
					if (model.size() > 6)
						break;
				}
			}
		}
		setVisible(true);
		int width = SparkManager.getMainWindow().getContentPane().getSize().width - 12;
		int height = model.size() * 22;
		contacts.setModel(model);
		setSize(width, height);
		contacts.updateUI();
//		setLocation(6, PositionCalculator.getInstance().getCmdPanelRelativeY());

	}
	
	public void showResultsForChat(String str){
		setLocation(6, PositionCalculator.getInstance().getCmdPanelRelativeY());
		showResults(str);
	}
	
	public void showResultsForInput(String str){
//		setLocation(92, 178);
		showResults(str);
	}
	
	public class InternalRenderer extends JLabel implements ListCellRenderer {

		/**
		 * Construct Default Renderer.
		 */
		public InternalRenderer() {
			setOpaque(true);
		}

		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {
			if (isSelected) {
				setBackground(list.getSelectionBackground());
				setForeground(list.getSelectionForeground());
			} else {
				setBackground(list.getBackground());
				setForeground(list.getForeground());
			}

			JLabel label = (JLabel) value;
			setText(label.getText());
			setIcon(label.getIcon());
			return this;
		}
	}

	public JList getContacts() {
		return contacts;
	}
	
	public Map<JLabel, String> getJIDMap(){
		return jidMap;
	}
	final MouseListener mouseListener = new MouseAdapter() {
		@Override
		public void mouseClicked(MouseEvent arg0) {
			if(!this.equals(arg0.getComponent().getClass()))
				setVisible(false);
		}
	};
	
	/**
	 * 统一  初始化搜索输入框与结果展示框之间的UI交互动作
	 * 
	 * 主要初始化：搜索输入框的文本变化事件、键盘按键事件
	 * 
	 * 不涉及结果具体的操作动作
	 *            
	 * 
	 * @param searchField 查询输入框
	 * @param contactSearchResult 结果显示面板
	 * @param method 事件处理动作用到的具体的方法
	 */
	public void initListener(final JTextComponent searchField,final ContactSearchResultPanel contactSearchResult,final String method){
		
		searchField.setText(Res.getString("message.search.for.other.people"));
		searchField.addFocusListener(new FocusListener() {
			@Override
			public void focusLost(FocusEvent e) {
				if(searchField.getText().equals("")){
					searchField.setText(Res.getString("message.search.for.other.people"));
				}
			}
			@Override
			public void focusGained(FocusEvent e) {
				if(searchField.getText().equals(Res.getString("message.search.for.other.people"))){
					searchField.setText("");
				}
			}
		});
		
		final DocumentListener searchFieldTextListener = new DocumentListener() {
			@Override
			public void removeUpdate(DocumentEvent arg0) {
				if(searchField.getText().equals("")){
					contactSearchResult.setVisible(false);
					return;
				}
				try {
					ContactSearchResultPanel.class.getMethod(method,
							String.class).invoke(
									contactSearchResult, searchField.getText());
					
				} catch (Exception e) {
					Log.error(e.toString());
				} 
				
			}
			
			@Override
			public void insertUpdate(DocumentEvent arg0) {
				if(searchField.getText().equals("")){
					contactSearchResult.setVisible(false);
					return;
				}
				try {
					ContactSearchResultPanel.class.getMethod(method,
							String.class).invoke(
									contactSearchResult, searchField.getText());
					
				} catch (Exception e) {
					Log.error(e.toString());
				} 
//				contactSearchResult.showResults(searchField.getText());
			}
			
			@Override
			public void changedUpdate(DocumentEvent arg0) {
				if(searchField.getText().equals("")){
					contactSearchResult.setVisible(false);
					return;
				}
				try {
					ContactSearchResultPanel.class.getMethod(method,
							String.class).invoke(
									contactSearchResult, searchField.getText());
					
				} catch (Exception e) {
					Log.error(e.toString());
				} 
//				contactSearchResult.showResults(searchField.getText());
			}
		}; 

		final KeyListener searchFieldKeyListener = new  KeyListener() {
			public void keyTyped(KeyEvent e) {
			}
			public void keyPressed(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_ENTER) {
					if(searchField.getText().equals("")) return;
					if (getContacts().getModel().getSize()>0) {
						setVisible(true);
						getContacts().requestFocus();
						getContacts().setSelectedIndex(0);
//						searchField.setText("");
					}else 
						return;
				}
				if (e.getKeyCode() == KeyEvent.VK_DOWN) {
					if(searchField.getText().equals("")) return;
					setVisible(true);
					getContacts().requestFocus();
					if (getContacts().getModel().getSize() > 0) {
						getContacts().setSelectedIndex(0);
					}else
						return;
				}
				if(e.getKeyCode() == KeyEvent.VK_ESCAPE){
					if(isVisible()){
						setVisible(false);
					}else {
						searchField.setText("");
					}
				}
			}
			public void keyReleased(KeyEvent e) {
				if(searchField.getText().equals("")) return;
				if(e.getKeyCode()==KeyEvent.VK_UP){
					showResults(searchField.getText());
				}
			}
		};
		
		searchField.getDocument().addDocumentListener(searchFieldTextListener);
		searchField.addKeyListener(searchFieldKeyListener);
		
		
	}
	
	/**
	 * 此方法为需要根据查询结果的值打开对应的聊天窗口的情况
	 * 
	 * 初始化鼠标及键盘事件
	 * 
	 * @param searchField
	 * @param contactSearchResult
	 */
	public void initListenerForChat(final JTextComponent searchField){
		initListener(searchField,this,"showResultsForChat");
		final MouseListener contactsMouseListener = new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					final JLabel label = (JLabel) getContacts()
					.getSelectedValue();
					String user =getJIDMap().get(label);
					if (user != null) {
						final String contactUsername = SparkManager
						.getUserManager().getUserNicknameFromJID(
								user);
						SparkManager.getChatManager().activateChat(user,
								contactUsername);
					}
				}
			}
		};
		
		final KeyListener contactsKeyListener = new KeyAdapter() {
			public void keyReleased(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_ENTER) {
					final JLabel label = (JLabel) getContacts().getSelectedValue();
					String user = getJIDMap().get(label);
					if (user != null) {
						searchField.setText("");
						final String contactUsername = SparkManager
								.getUserManager().getUserNicknameFromJID(user);
						SparkManager.getChatManager().activateChat(user,
								contactUsername);
						
					}
				}
			}
			@Override
			public void keyPressed(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_UP){
					if(getContacts().isSelectedIndex(0)){
						searchField.requestFocus();
						
					}
				}
				if(e.getKeyCode() == KeyEvent.VK_ESCAPE){
					setVisible(false);
				}
			}
		};
		getContacts().addKeyListener(contactsKeyListener);
		getContacts().addMouseListener(contactsMouseListener);
	}
	
	
	public void initListenerForLocation(final JTextComponent searchField){
		initListener(searchField,this,"showResultsForChat");
		final MouseListener contactsMouseListener = new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					final JLabel label = (JLabel) getContacts()
					.getSelectedValue();
					String user =getJIDMap().get(label);
					if (user != null) {
						ContactItem item = SparkManager.getContactList().getContactItemByJID(user);
						SparkManager.getContactList().contactItemDoubleClicked(item);
					}
				}
			}
		};
		
		final KeyListener contactsKeyListener = new KeyAdapter() {
			public void keyReleased(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_ENTER) {
					final JLabel label = (JLabel) getContacts().getSelectedValue();
					String user = getJIDMap().get(label);
					if (user != null) {
						ContactItem item = SparkManager.getContactList().getContactItemByJID(user);
						SparkManager.getContactList().contactItemDoubleClicked(item);
					}
				}
			}
			@Override
			public void keyPressed(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_UP){
					if(getContacts().isSelectedIndex(0)){
						searchField.requestFocus();
						
					}
				}
				if(e.getKeyCode() == KeyEvent.VK_ESCAPE){
					setVisible(false);
				}
			}
		};
		getContacts().addKeyListener(contactsKeyListener);
		getContacts().addMouseListener(contactsMouseListener);
	}
	
	/**
	 * 此方法为需要将查询结果的值填充到列表的情况
	 * 
	 * 初始化鼠标及键盘事件
	 * 
	 * @param searchField 查找输入框
	 * @param contactSearchResult 查找结果框
	 * @param destInput 填充目标列表
	 */
	public void initListenerForInput(final JTextComponent searchField,final DefaultListModel destInput){
		initListener(searchField, this,"showResultsForInput");
		final MouseListener contactsMouseListener = new MouseAdapter() {
	    	public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					final JLabel label = (JLabel) getContacts()
					.getSelectedValue();
			String user = getJIDMap().get(label);
			String temp = org.jivesoftware.spark.util.StringUtils.combineWithBracket(SparkManager.getUserManager().getUserNicknameFromJID(user), user);
			if (user != null && !destInput.contains(temp)) {
				destInput.addElement(temp);
				searchField.setText("");
				searchField.requestFocus();
			}else{
				setVisible(false);
			}
				}
			}
		};
	    
	    final KeyListener contactsKeyListener = new KeyAdapter() {
	    	public void keyReleased(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_ENTER) {
					final JLabel label = (JLabel) getContacts()
							.getSelectedValue();
					String user = getJIDMap().get(label);
					String temp = org.jivesoftware.spark.util.StringUtils.combineWithBracket(SparkManager.getUserManager().getUserNicknameFromJID(user), user);
					if (user != null && !destInput.contains(temp)) {
						destInput.addElement(temp);
						searchField.setText("");
						searchField.requestFocus();
					}else{
						setVisible(false);
					}
				}
				if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
					setVisible(false);
				}
			}
			@Override
			public void keyPressed(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_UP){
					if(getContacts().isSelectedIndex(0)){
						searchField.requestFocus();
					}
				}
				if(e.getKeyCode() == KeyEvent.VK_ESCAPE){
					setVisible(false);
				}
			}
		};
		getContacts().addKeyListener(contactsKeyListener);
		getContacts().addMouseListener(contactsMouseListener);
	}
		
}